/*
 * Copyright (c) 2025 EasyAdmin
 * All rights reserved.
 *
 * This file is part of the [EasAdmin] project.
 * Unauthorized copying of this file, via any medium, is strictly prohibited.
 * Proprietary and confidential.
 *
 * Author: EasyAdmin ( 1073602@qq.com )
 * Website: https://www.xhxiao.com
 */
package com.easy.module.log.service.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.framework.common.utils.Func;
import com.easy.framework.common.utils.ServletUtils;
import com.easy.framework.common.utils.ip.AddressUtils;
import com.easy.framework.common.utils.ip.IpUtils;
import com.easy.framework.security.service.ILoginLogService;
import com.easy.module.log.entity.SysLoginLog;
import com.easy.module.log.mapper.SysLoginLogMapper;
import com.easy.module.log.query.SysLoginLogQuery;
import com.easy.module.log.service.ISysLoginLogService;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 登录日志 Service业务
 *
 * @author EasyAdmin ( 1073602@qq.com )
 * @date 2025-08-19
 */
@Service
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLog> implements ISysLoginLogService, ILoginLogService {
    /**
     * 获取查询对象
     *
     * @param query
     * @return
     */
    @Override
    public LambdaQueryWrapper<SysLoginLog> getWrapper(SysLoginLogQuery query) {
        LambdaQueryWrapper<SysLoginLog> wrapper = lambdaQueryOptional(query).orElse(lambdaQueryWrapper());
        if (Func.isNotEmpty(query)) {
            if (Func.isNotEmpty(query.getParams())) {
                String beginTime = MapUtil.getStr(query.getParams(), "beginTime");
                String endTime = MapUtil.getStr(query.getParams(), "endTime");
                if (Func.isNotEmpty(beginTime)) {
                    wrapper.ge(SysLoginLog::getLoginAt, beginTime);
                }
                if (Func.isNotEmpty(endTime)) {
                    wrapper.le(SysLoginLog::getLoginAt, endTime);
                }
            }
        }
        wrapper.orderByDesc(SysLoginLog::getId);
        return wrapper;
    }

    /**
     * 查询操作日志记录列表
     *
     * @param query 操作日志记录
     * @return 操作日志记录
     */
    @Override
    public List<SysLoginLog> queryList(SysLoginLogQuery query) {
        return list(getWrapper(query));
    }


    /**
     * 新增操作日志记录
     *
     * @param username 用户名
     * @param grantType 登录模式
     * @param isSuccess 是否登录成功
     * @param userAgent  请求头User-Agent
     * @param ip  请求IP地址
     * @param msg 信息
     * @return
     */
    @Async
    @Override
    public CompletableFuture<Boolean> addAsync(String username, String grantType, Boolean isSuccess,String userAgent,String ip, String msg) {
        SysLoginLog dto = new SysLoginLog();
        dto.setUsername(username);
        dto.setGrantType(grantType);
        dto.setStatus(isSuccess ? 0 : 1);
        dto.setMsg(msg);
        UserAgent ua = UserAgent.parseUserAgentString(userAgent);
        dto.setBrowser(ua.getBrowser().getName());
        dto.setOs(ua.getOperatingSystem().getName());
        dto.setDevice(ua.getOperatingSystem().getDeviceType().toString());
        dto.setIp(ip);
        dto.setLocation(AddressUtils.getRealAddressByIP(true, ip));
        dto.setLoginAt(new Date());
        System.out.println("----------------:" + JSON.toJSONString(dto));
        return CompletableFuture.completedFuture(save(dto));
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void clean() {
        baseMapper.clean();
    }
}
